// 存储登陆名和token

import http from "@/utils/request";
import api from "@/utils/api";
import router from '@/router'
import consts from '@/utils/consts'

const userKey = 'Email'
const pwdKey = 'password'

const state = {
    token: '',
    // email: ''
    // email: 'chaolin.yin@huadaocart.com'
    email: localStorage.getItem(userKey),
    password: localStorage.getItem(pwdKey),
};
const getters = {
    token: (state) => state.token,
    email: (state) => state.email,
    password: (state) => state.password
};
const actions = {
    login({ commit }, params) {
        const emailWithoutSuffix = params.Email
        params.Email = params.Email + consts.emailSuffix
        http
            .fetchPost(api.login, params, "登录中...")
            .then(data => {
                commit('setToken', data);
                commit('setEmail', emailWithoutSuffix);
                commit('setPwd', params.Password);

                console.log('pushed to main application');

                if (router.history.current.query.redirect) {
                    router.push({ path: router.history.current.query.redirect });
                } else {
                    router.push({ path: "/main" });
                }
                // router.push({ path: "/main" });
            })
            .catch(err => {
            });
    },
    logout({ commit }) {
        commit('setToken', null);
        commit('setEmail', null);
        commit('setPwd', null);
        localStorage.removeItem(userKey);
        localStorage.removeItem(pwdKey);
        router.push({ path: "/login" });
    }
};
const mutations = {
    setToken: (state, token) => (state.token = token),
    setEmail: (state, email) => { state.email = email; localStorage.setItem(userKey, email) },
    setPwd: (state, password) => {
        state.password = password;
        localStorage.setItem(pwdKey, password)
    }
};
export default {
    state,
    getters,
    actions,
    mutations
}

// const user = {
//     state: {
//         token: getToken(),
//         name: '',
//     },

//     mutations: {
//         SET_TOKEN: (state, token) => {
//             state.token = token;
//             setToken(token);
//         },
//         SET_NAME: (state, name) => {
//             state.name = name;
//         },
//     },

// }

// export default user
